package ru.spb.osll.myfit.server.parser;

import java.util.LinkedList;
import java.util.Vector;
import java.util.regex.Pattern;

import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableCell;
import ru.spb.osll.myfit.common.TableStyle;

public class TableElementParser implements IAccumulatingParser {
  private final Pattern TABLE_PATTERN = Pattern.compile("\\|.*\\|");
  private final Pattern IMPORT_PATTERN = Pattern.compile("\\|\\s*Import\\s*\\|");
  
  private LinkedList<String> m_tableRows = new LinkedList<String>();
  
  @Override
  public PageElement reset() {
    if(m_tableRows.isEmpty()){
      return null;
    }
    Table table = createTable(TableStyle.UNKNOWN_FIXTURE); 
    m_tableRows.clear();
    return table;
  }

  @Override
  public boolean matches(String line) {
    return TABLE_PATTERN.matcher(line).matches();
  }

  @Override
  public PageElement parse(String line) {
    m_tableRows.add(line.trim());
    return null;
  }
  
  private Table createTable(TableStyle style){
    String tableHeader = m_tableRows.peek();
    if(isImportTable(tableHeader)){
      return null;
    }
    
    Table table = new Table(style);
    for(String row: m_tableRows){
      String[] cells = row.split("\\|");
      Vector<TableCell> cellslist = new Vector<TableCell>();
      int size = cells.length;
      for(int i = 1; i < size; i++){
        cellslist.add(new TableCell(cells[i]));
      }
      table.addLine(cellslist);
    }
    return table;
  }
  
  private boolean isImportTable(String tableHeader){
    return IMPORT_PATTERN.matcher(tableHeader).matches();
  }
}
